package com._5704.website.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

/**
 * redis的工具
 */
@Component
public class RedisUtil {

    private static RedisTemplate<String, Object> redisTemplate;
    // 默认过期时间
    private static Long defaultTime;

    @Resource
    private void setRedisTemplate(RedisTemplate<String, Object> redisTemplateIn) {
        redisTemplate = redisTemplateIn;
    }

    @Value("${spring.redis.defaultTime}")
    public  void setDefaultTime(Long defaultTimeIn) {
        defaultTime = defaultTimeIn;
    }

    /**
     * 添加value，默认时间
     * @param key key
     * @param value 值
     */
    public static void  setValue(String key, Object value){
            redisTemplate.opsForValue().set(key,value,defaultTime,TimeUnit.SECONDS);
    }

    /**
     * 天降value
     * @param key 键
     * @param value 值
     * @param time 时长， 秒
     */
    public static void  setValue(String key,Object value,long time){
        redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
    }

    /**
     * 获得值
     * @param key 键
     * @param <T> 返回值的类型
     * @return
     */
    public static <T> T getValue(String key){
        return (T) redisTemplate.opsForValue().get(key);
    }

    public static void  delete(String key){
        redisTemplate.delete(key);
    }

    public static void setValue(String key, Object hKey, Object val){
        redisTemplate.opsForHash().put(key,hKey,val);
    }

    public static <T> T getValue(String key,Object hKey){
        return (T) redisTemplate.opsForHash().get(key,hKey);
    }
    public static boolean isExist(@NotNull String key,Object hKey){
        return redisTemplate.opsForHash().hasKey(key,hKey);
    }
    public static boolean isExist(@NotNull String key){
        return redisTemplate.hasKey(key);
    }
}
